package helloWorld.musicplayer;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

public class UrlPlayer {

	public boolean play(String location) {
		boolean canPlay = true;
		
		if (player != null)
			stop();

		if (initPlayer(location))
			playerThread.start();
		else
			canPlay = false;

		return canPlay;
	}

	public void stop() {
		if (player != null)
			player.close();
		player = null;
	}

	public boolean isPlaying() {
		boolean isPlaying = false;

		if (playerThread != null && playerThread.isAlive())
			isPlaying = true;

		return isPlaying;
	}

	private boolean initPlayer(String location) {
		boolean success = false;

		playerThread = new PlayerThread();

		try {
			URL url = new URL(location);
			InputStream fin = url.openStream();
			InputStream input = new BufferedInputStream(fin);
			this.player = new Player(input);
			success = true;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JavaLayerException e) {
			e.printStackTrace();
		}
		return success;
	}

	private Player player = null;
	private PlayerThread playerThread = null;

	private class PlayerThread extends Thread {
		public void run() {
			if (player != null)
				try {
					player.play();
				} catch (JavaLayerException e) {
					e.printStackTrace();
				}
		}
	}

}
